from enum import Enum
from typing import Optional
from datetime import datetime
from pydantic import BaseModel, EmailStr, Field, field_validator
import re

class UserRole(str, Enum):
    """用户角色枚举"""
    STUDENT = "student"
    COUNSELOR = "counselor"
    ADMIN = "admin"

class UserBase(BaseModel):
    """用户基础信息"""
    name: str = Field(..., min_length=2, max_length=50, description="用户姓名")
    email: EmailStr = Field(..., description="用户邮箱")
    phone_number: str = Field(..., min_length=11, max_length=11, description="用户手机号")


class UserCreate(UserBase):
    """创建用户的请求模型"""
    password: str = Field(..., min_length=8, description="用户密码")
    role: str = Field(..., description="用户角色")
    account_id: str = Field(..., description="用户账号ID")

    @field_validator('role')
    def role_must_be_valid(cls, v):
        try:
            UserRole(v)
            return v
        except ValueError:
            raise ValueError(f'角色必须是 {", ".join([role.value for role in UserRole])}')

class StudentCreate(BaseModel):
    """创建学生的请求模型"""
    academy: str = Field(..., description="学院")
    major: str = Field(..., description="专业")
    class_: str = Field(..., alias="class", description="班级")

class CounselorCreate(BaseModel):
    """创建辅导员的请求模型"""
    department: str = Field(..., description="部门")
    office_location: Optional[str] = Field(None, description="办公室位置")

class UserUpdate(BaseModel):
    """更新用户的请求模型"""
    name: Optional[str] = Field(None, min_length=2, max_length=50, description="用户姓名")
    email: Optional[EmailStr] = Field(None, description="用户邮箱")
    phone_number: Optional[str] = Field(None, min_length=11, max_length=11, description="用户手机号")
    password: Optional[str] = Field(None, min_length=8, description="用户密码")

    @field_validator('phone_number')
    def phone_must_be_valid(cls, v):
        if v and not re.match(r'^\d{11}$', v):
            raise ValueError('手机号必须是11位数字')
        return v

class UserInDB(UserBase):
    """数据库中的用户模型"""
    id: int
    account_id: Optional[str] = None
    role: str
    is_active: bool
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True

class StudentResponse(BaseModel):
    """学生响应模型"""
    user_id: int
    academy: str
    major: str
    class_: str = Field(..., alias="class")

    class Config:
        from_attributes = True

class CounselorResponse(BaseModel):
    """辅导员响应模型"""
    department: str
    office_location: Optional[str] = None

    class Config:
        from_attributes = True

class UserResponse(UserBase):
    """API响应中的用户模型"""
    id: int
    name: str
    account_id: Optional[str] = None
    role: str

    class Config:
        from_attributes = True